$(function() {
     parent.$.messager.progress('close');

     $('#form').form({
         url : contextPath+"/tradecuscontract/editTradeCusContract.action",
         onSubmit : function() {
             parent.$.messager.progress({
                 title : var_alert_title,
                 text : var_data_processing
             });
             //检查Form参数合法性,返回false不提交
            if(!checkForm()){
                parent.$.messager.progress('close');
                 return false;
            }else{
            	packingDatas();
            }
         },
         success : function(data) {
             parent.$.messager.progress('close');
             data = JSON.parse(data);
             if(data && "success" == data.result){
            	 parent.$.messager.alert(var_alert_title, data.msg, 'info');
            	 parent.$.modalDialog.handler.dialog('close');
           	     parent.$.modalDialog.openner_dataGrid.datagrid('reload');
             } else {
                 parent.$.messager.alert(var_common_error, data.msg, 'error');
             }
         }
     });
});

//在提交之前封装数据
function packingDatas(){
	var dtlrows = dtlDatagrid.datagrid('getRows');
	var  tradeCusContractDtlIdsStr = "";
	var  itemVal = "";
	var  itemSizeVal = "";
	var  totalContVal = "";
	var  boxOfContVal = "";
	var  totalBoxsVal = "";
	var  pcsOfBoxVal = "";
	var  totalPcsVal = "";
	var  mtwoOfContVal = "";
	var  totalMtwoVal = "";
	var  fobUnitPriceVal = "";
	var  amountVal = "";
	for(var i=0;i<dtlrows.length;i++){
		if(isEmpty(dtlrows[i].id)){
			tradeCusContractDtlIdsStr += " ,";
		}else{
			tradeCusContractDtlIdsStr += dtlrows[i].id+",";
		}
		itemVal += dtlrows[i].item+",";
		itemSizeVal += dtlrows[i].itemSize+",";
		totalContVal += dtlrows[i].totalCont+",";
		boxOfContVal += dtlrows[i].boxOfCont+",";
		totalBoxsVal += dtlrows[i].totalBoxs+",";
		pcsOfBoxVal += dtlrows[i].pcsOfBox+",";
		totalPcsVal += dtlrows[i].totalPcs+",";
		mtwoOfContVal += dtlrows[i].mtwoOfCont+",";
		totalMtwoVal += dtlrows[i].totalMtwo+",";
		fobUnitPriceVal += dtlrows[i].fobUnitPrice+",";
		amountVal += dtlrows[i].amount+",";
	}

	$("#tradeCusContractDtlIdsStr").val(tradeCusContractDtlIdsStr);
	$("#itemDtl").val(itemVal);
	$("#itemSizeDtl").val(itemSizeVal);
	$("#totalContDtl").val(totalContVal);
	$("#boxOfContDtl").val(boxOfContVal);
	$("#totalBoxsDtl").val(totalBoxsVal);
	$("#pcsOfBoxDtl").val(pcsOfBoxVal);
	$("#totalPcsDtl").val(totalPcsVal);
	$("#mtwoOfContDtl").val(mtwoOfContVal);
	$("#totalMtwoDtl").val(totalMtwoVal);
	$("#fobUnitPriceDtl").val(fobUnitPriceVal);
	$("#amountDtl").val(amountVal);
}

//检查表单数据合法性
function checkForm(){
	var isValid = true;
	
	if (editcount > 0) {
		$.messager.alert(var_alert_title, var_record_editting_tip);
		return false;
	}

	var cusAddress = $("#form").find("[name='cusAddress']").validatebox({
	    required: true
	});
	isValid = isValid && cusAddress.validatebox('isValid');

	var cusTelFax = $("#form").find("[name='cusTelFax']").validatebox({
	    required: true
	});
	isValid = isValid && cusTelFax.validatebox('isValid');

	var cusEmail = $("#form").find("[name='cusEmail']").validatebox({
	    required: true
	});
	isValid = isValid && cusEmail.validatebox('isValid');
	
	//检查细表
	var dtlrows = dtlDatagrid.datagrid('getRows');
	var itemFlag = true;
	var fobSizeFlag = true;
	var totalContFlag = true;
	var boxOfContFlag = true;
	var pcsOfBoxFlag = true;
	var fobUnitPriceFlag = true;
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].item)){
			itemFlag = false;
			break;
		}
	}
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].itemSize)){
			fobSizeFlag = false;
			break;
		}
	}
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].totalCont)){
			totalContFlag = false;
			break;
		}
	}
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].boxOfCont)){
			boxOfContFlag = false;
			break;
		}
	}
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].pcsOfBox)){
			pcsOfBoxFlag = false;
			break;
		}
	}
	for (var i = 0; i < dtlrows.length; i++) {
		if(isEmpty(dtlrows[i].fobUnitPrice)){
			fobUnitPriceFlag = false;
			break;
		}
	}
	
	if(!itemFlag || !fobSizeFlag || !totalContFlag || !boxOfContFlag || !pcsOfBoxFlag || !fobUnitPriceFlag){
		parent.$.messager.alert(var_alert_title, var_dtl_required, 'info');
		isValid = false;
	}
	
	return isValid;
}

//细表datagrid
var dtlDatagrid;
$(function(){
	dtlDatagrid = $('#dtlDatagrid').datagrid({
		title : var_dtl_title,
		url: contextPath + '/tradecuscontractdtl/getTradeCusContractDtlListData.action?id='+var_tradeCusContract_id,
		singleSelect:true,
		width : 1020,
		height : 250,
		columns : [[
		     {title:var_column_serialnumber,field:'id',width:27,sortable:true,
		    	 sorter:function(a,b){
		    		 return (a>b?1:-1);
		    	 }
		     },
			{field : 'item',title : var_column_item,width : 94,editor : 'text'},
			{field : 'itemSize',title : var_column_itemSize,width : 100,editor : 'text'},
			{field : 'totalCont',title : var_column_totalCont,width : 75,editor : {type:'numberbox',options:{min:0,required:true,value:0}}},
			{field : 'boxOfCont',title : var_column_boxCont,width : 75,editor : {type:'numberbox',options:{min:0,required:true,value:0}}},
			{field : 'totalBoxs',title : var_column_totalBox,width : 75},
			{field : 'pcsOfBox',title : var_column_pcsBox,width : 75,editor : {type:'numberbox',options:{min:0,required:true,value:0}}},
			{field : 'totalPcs',title : var_column_totalPcs,width : 75},
			{field : 'mtwoOfCont',title : var_column_mtwoCont,width : 75},
			{field : 'totalMtwo',title : var_column_totalMtwo,width : 75},
			{field : 'fobUnitPrice',title : var_column_fobunitPrice,width : 75,editor : {type:'numberbox',options:{precision:2,min:0,required:true,value:0.00}}},
			{field : 'amount',title : var_column_amount,width : 75},
			{field : 'action',title : var_column_opt,width : 90,align : 'center',formatter : function(value, row, index) {
												if (row.editing) {
													var s = '<a href="#" onclick="saverow(this)">'+var_column_save+'</a> ';
													var c = '<a href="#" onclick="cancelrow(this)">'+var_cancel+'</a>';
													return s + c;
												} else {
													var e = '<a href="#" onclick="editrow(this)">'+var_column_edit+'</a> ';
													var d = '<a href="#" onclick="deleterow(this)">'+var_column_delete+'</a>';
													return e + d;
												}
											}}, 
			] ],
		toolbar : [ 
		           {text : var_column_increase,iconCls : 'icon-add',handler : addrow}, 
			   	   {text : var_column_insert,iconCls : 'icon-add',handler : insertrow}
		],
		onBeforeEdit : function(index, row) {
			row.editing = true;
			updateActions(index);
			dtlDatagrid.datagrid('refreshRow', index);
			if(editcount<1){
				editcount++;
			}
		},
		onAfterEdit : function(index, row) {
			row.editing = false;
			updateActions(index);
			dtlDatagrid.datagrid('refreshRow', index);
			editcount--;
		},
		onCancelEdit : function(index, row) {
			row.editing = false;
			updateActions(index);
			dtlDatagrid.datagrid('refreshRow', index);
			editcount--;
		}
	});
		
	
	$('#totalTab').datagrid({
		width : 1020,
		columns : [[
			{field : 'name1',title : var_tatal_amount_str,width : 222},
			{field : 'name2',title : var_tradeCusContract_totTotalConts,width : 75},
			{field : 'name3',title : '--------',width : 75},
			{field : 'name4',title : var_tradeCusContract_totTotalBoxs,width : 75},
			{field : 'name5',title : '-----',width : 75},
			{field : 'name6',title : var_tradeCusContract_totTotalPcs,width : 75},
			{field : 'name7',title : '--------',width : 75},
			{field : 'name8',title : var_tradeCusContract_totTotalMtwos,width : 75},
			{field : 'name9',title : '',width : 75},
			{field : 'name10',title : var_tradeCusContract_totTotalAmount,width : 75},
			{field : 'name11',title : '',width : 90}
		]]
	});
	
	$('#amountEnTab').datagrid({
		width : 1020,
		columns : [[
			{field : 'name12',title : 'SAY TOTAL U.S. DOLLARS:<font color="red">'+var_tradeCusContract_totTotalAmountEn+"</font>",width : 1020}
		]]
	});
});


//计算行金额和总额
function setEditing(rowIndex){
	parent.$.messager.progress({
        title : var_alert_title,
        text : var_loadMsg
    });
		
	var editors = dtlDatagrid.datagrid('getEditors', rowIndex);
	var itemEditor = editors[0];
	var itemSizeEditor = editors[1];
	var totalContEditor = editors[2];
	var boxContEditor = editors[3];
	var pcsBoxEditor = editors[4];
	var unitPriceFobEditor = editors[5];
	
	var itemLenght = 0.0;
	var itemWidth = 0.0;
	
	var item_val = itemEditor.target.val();
	var itemsize_val = itemSizeEditor.target.val();
	if(!isEmpty(itemsize_val)){
		var itemsizes = itemsize_val.split("*");
		if((!isEmpty(itemsizes)) && (itemsizes.length > 0)){
			itemLenght = formatFloat(itemsizes[0]/100,2);
			itemWidth = formatFloat(itemsizes[1]/100,2);
		}
	}
	
	var totalcont_val = totalContEditor.target.val();
	var boxcont_val = boxContEditor.target.val();
	var totalbox = formatFloat(totalcont_val * boxcont_val,2);
	
	var pcsbox_val =  pcsBoxEditor.target.val();
	var totalpcs = formatFloat(totalbox * pcsbox_val,2);
	var mtwocont_val = formatFloat(boxcont_val*pcsbox_val*itemLenght*itemWidth,2);
	var totalmtwo = formatFloat(totalcont_val * mtwocont_val,2);
	var var_unit_price = unitPriceFobEditor.target.val();
	var amount = formatFloat(totalmtwo * var_unit_price,2);
	
	dtlDatagrid.datagrid('updateRow', {
        index: rowIndex,
        row: {
        	item:item_val,
        	itemSize:itemsize_val,
        	totalCont:totalcont_val,
        	boxOfCont:boxcont_val,
        	totalBoxs:totalbox,
        	pcsOfBox:pcsbox_val,
            totalPcs:totalpcs,
            mtwoOfCont:mtwocont_val,
            totalMtwo:totalmtwo,
            fobUnitPrice:var_unit_price,
            amount:amount,
            editing:false
        },
    });
	
	//计算总额
	var dtlrows = dtlDatagrid.datagrid('getRows');
	var totalContainers = 0;//总柜数
	var totalBoxes = 0;//总盒数
	var totalPackages = 0;//总箱数
	var totalMtwos = 0.00;//总平方米
	var totalAmounts = 0.00;//总金额
	var totalAmountsStr = "";//总金额英文字符串
	for (var i = 0; i < dtlrows.length; i++) {
		totalContainers += formatFloat(dtlrows[i].totalCont,2);
		totalBoxes += dtlrows[i].totalBoxs;
		totalPackages += dtlrows[i].totalPcs;
		totalMtwos += dtlrows[i].totalMtwo;
		totalAmounts += dtlrows[i].amount;
	}
	
	if(totalAmounts > 0){
		$.ajax({
            type: "post",
            url: contextPath+"/amounttrans/transFormEn.action",
            data: {"amount":formatFloat(totalAmounts,2)},
            success: function(data){
            	totalAmountsStr = data.amountEn;
            	$('#totTotalAmountEn').val(totalAmountsStr);
            	$('#amountEnTab').datagrid({
        			width : 1020,
        			columns : [[
        				{field : 'name12',title : 'SAY TOTAL U.S. DOLLARS:<font color="color">'+totalAmountsStr+"</font>",width : 1020}
        			]]
        		});
            }//操作成功后的操作！msg是后台传过来的值
        }); 
	}

	$('#totTotalConts').val(totalContainers);
	$('#totTotalBoxs').val(totalBoxes);
	$('#totTotalPcs').val(totalPackages);
	$('#totTotalMtwos').val(totalMtwos);
	$('#totTotalAmount').val(totalAmounts);
	
	$('#totalTab').datagrid({
		width : 1020,
		columns : [[
			{field : 'name1',title : var_tatal_amount_str,width : 222},
			{field : 'name2',title : totalContainers,width : 75},
			{field : 'name3',title : '--------',width : 75},
			{field : 'name4',title : totalBoxes,width : 75},
			{field : 'name5',title : '-----',width : 75},
			{field : 'name6',title : totalPackages,width : 75},
			{field : 'name7',title : '--------',width : 75},
			{field : 'name8',title : formatFloat(totalMtwos,2),width : 75},
			{field : 'name9',title : '',width : 75},
			{field : 'name10',title : formatFloat(totalAmounts,2),width : 75},
			{field : 'name11',title : '',width : 90}
		]]
	});
	
	parent.$.messager.progress('close');//关闭进度条
	
	editcount--;
}

//删除后进行计算总额
function caculateAfterDel(){
	parent.$.messager.progress({
        title : var_alert_title,
        text : var_loadMsg
    });
	
	//计算总额
	var dtlrows = dtlDatagrid.datagrid('getRows');
	var totalContainers = 0;//总柜数
	var totalBoxes = 0;//总盒数
	var totalPackages = 0;//总箱数
	var totalMtwos = 0.00;//总平方米
	var totalAmounts = 0.00;//总金额
	var totalAmountsStr = "";//总金额英文字符串
	for (var i = 0; i < dtlrows.length; i++) {
		totalContainers += formatFloat(dtlrows[i].totalCont,2);
		totalBoxes += dtlrows[i].totalBoxs;
		totalPackages += dtlrows[i].totalPcs;
		totalMtwos += dtlrows[i].totalMtwo;
		totalAmounts += dtlrows[i].amount;
	}
	
	if(totalAmounts > 0){
		$.ajax({
            type: "post",
            url: contextPath+"/amounttrans/transFormEn.action",
            data: {"amount":formatFloat(totalAmounts,2)},
            success: function(data){
            	totalAmountsStr = data.amountEn;
            	$('#totTotalAmountEn').val(totalAmountsStr);
            	$('#amountEnTab').datagrid({
        			width : 1020,
        			columns : [[
        				{field : 'name12',title : 'SAY TOTAL U.S. DOLLARS:<font color="color">'+totalAmountsStr+"</font>",width : 1020}
        			]]
        		});
            }
        }); 
	}

	$('#totTotalConts').val(totalContainers);
	$('#totTotalBoxs').val(totalBoxes);
	$('#totTotalPcs').val(totalPackages);
	$('#totTotalMtwos').val(totalMtwos);
	$('#totTotalAmount').val(totalAmounts);
	$('#totalTab').datagrid({
		width : 1020,
		columns : [[
			{field : 'name1',title : var_tatal_amount_str,width : 222},
			{field : 'name2',title : totalContainers,width : 75},
			{field : 'name3',title : '--------',width : 75},
			{field : 'name4',title : totalBoxes,width : 75},
			{field : 'name5',title : '-----',width : 75},
			{field : 'name6',title : totalPackages,width : 75},
			{field : 'name7',title : '--------',width : 75},
			{field : 'name8',title : formatFloat(totalMtwos,2),width : 75},
			{field : 'name9',title : '',width : 75},
			{field : 'name10',title : formatFloat(totalAmounts,2),width : 75},
			{field : 'name11',title : '',width : 90}
		]]
	});
	
	parent.$.messager.progress('close');//关闭进度条
	
	editcount--;
}

function updateActions(index){
	dtlDatagrid.datagrid('updateRow',{
		index: index,
		row:{}
	});
}
//取得行索引
function getRowIndex(target){
	var tr = $(target).closest('tr.datagrid-row');
	return parseInt(tr.attr('datagrid-row-index'));
}

//更新每行的值，为保证数据正确性,一次只能操作一条记录
var editcount = 0;
var itemEditor;
var itemSizeEditor;
function editrow(target) {
	if (editcount > 0) {
		$.messager.alert(var_alert_title, editcount + var_record_editting_cantnot_increase);
		return;
	}
	
	var rowindex = getRowIndex(target);
	dtlDatagrid.datagrid('beginEdit', rowindex);
	
	//给项目名称和规格绑定onclick事件，可选拔
	var editors = dtlDatagrid.datagrid('getEditors', rowindex);
	itemEditor = editors[0];
	itemSizeEditor = editors[1];
	itemEditor.target.bind('click', function(){
		selectFoCost();
	});
	itemSizeEditor.target.bind('click', function(){
		selectFoCost();
	});
}

function deleterow(target) {
	$.messager.confirm(var_alert_title, var_del_confirm, function(r) {
		if (r) {
			dtlDatagrid.datagrid('deleteRow', getRowIndex(target));
			caculateAfterDel();//重新统计
		}
	});
}

function saverow(target) {
	var var_row_index = getRowIndex(target);
	setEditing(var_row_index);
	dtlDatagrid.datagrid('endEdit', var_row_index);
}

function cancelrow(target) {
	dtlDatagrid.datagrid('cancelEdit', getRowIndex(target));
}

//增加一行，与insertrow不同，这是增加到最后一行
function addrow() {
	if (editcount > 0) {
		$.messager.alert(var_alert_title, editcount + var_record_editting_cantnot_increase);
		return;
	}
	dtlDatagrid.datagrid('appendRow', {
			totalCont:0.0,
			boxOfCont:0.0,
			totalBoxs:0.0,
			pcsOfBox:0.0,
			totalPcs:0.0,
			mtwoOfCont:0.0,
			totalMtwo:0.0,
			fobUnitPrice:0.0,
			amount:0.0
	});
}

//插入一行，与addrow不同，这是在选定的一行前新增一行，默认增加到第一行
function insertrow() {
	if (editcount > 0) {
		$.messager.alert(var_alert_title, editcount + var_record_editting_cantnot_increase);
		return;
	}
	var row = dtlDatagrid.datagrid('getSelected');
	var index;
	if (row){
		index = dtlDatagrid.datagrid('getRowIndex', row);
	} else {
		index = 0;
	}
	dtlDatagrid.datagrid('insertRow', {
		index: index,
		row:{
			totalCont:0.0,
			boxOfCont:0.0,
			totalBoxs:0.0,
			pcsOfBox:0.0,
			totalPcs:0.0,
			mtwoOfCont:0.0,
			totalMtwo:0.0,
			fobUnitPrice:0.0,
			amount:0.0
		}
	});
	dtlDatagrid.datagrid('selectRow',index);
	dtlDatagrid.datagrid('beginEdit',index);
	
	//给项目名称和规格绑定onclick事件，可选拔
	var editors = dtlDatagrid.datagrid('getEditors', index);
	itemEditor = editors[0];
	itemSizeEditor = editors[1];
	itemEditor.target.bind('click', function(){
		selectFoCost();
	});
	itemSizeEditor.target.bind('click', function(){
		selectFoCost();
	});
}

//保存全部和取消全部编辑(两个功能暂时不用)
function saveall() {
	dtlDatagrid.datagrid('acceptChanges');
}
function cancelall() {
	dtlDatagrid.datagrid('rejectChanges');
}

//选择客户
function selectCustomer(){
	showSecondDialog(var_crmcus_select_title,contextPath+"/crmcustomer/toChooseListCrmcustomer.action","crmcus");
}

//选择fob成本记录
function selectFoCost(){
	showSecondDialog(var_fobcost_select_title,contextPath+"/fobcost/toChooseListFobCost.action","fobcost");
}

var chooseids;
var addresss;
var telFaxs;
var emails;
//检查选择的客户
function checkCrmCusChoose(){
	chooseids = [];
	var rows = parent.$.modalDialog2.handler.find('#dataGridCrmCus').datagrid('getSelections');
	if (rows.length == 0) {
		parent.$.messager.alert(var_alert_title, var_crmcus_please_select, 'info');
   		return false;
	}
	for (var i = 0; i < rows.length; i++) {
		chooseids.push(rows[i].id);
		addresss= rows[i].address;
		telFaxs = rows[i].telFax;
		emails = rows[i].email;
	}
	
	if(chooseids.length != 1 ){
		parent.$.messager.alert(var_alert_title, var_crmcus_onlyone_select, 'info');
		return false;
	}

	return true;
}
//选定客户记录后，将值赋给父页面
function selectTradeCusContract(){
	parent.$.messager.progress({
        title : var_alert_title,
        text : var_loadMsg
    });
	
	if(!checkCrmCusChoose()){
		parent.$.messager.progress('close');
        return false;
     }else{
    	$("#cusAddress").html(addresss);
 		$("#cusTelFax").attr("value",telFaxs);
 		$("#cusEmail").attr("value",emails);
    	 parent.$.messager.progress('close');
     }
	
	parent.$.modalDialog2.handler.dialog('close');//要先关闭弹出框，才能另外打开
}

var fobCostItem;
var fobCostISize;
//检查选择的Fob成本
function checkFobCostChoose(){
	chooseids = [];
	var rows = parent.$.modalDialog2.handler.find('#dataGridFobCost').datagrid('getSelections');
	if (rows.length == 0) {
		parent.$.messager.alert(var_alert_title, var_fobcost_please_select, 'info');
   		return false;
	}
	for (var i = 0; i < rows.length; i++) {
		chooseids.push(rows[i].id);
		fobCostItem= rows[i].item;
		fobCostISize = rows[i].fobSize;
	}
	
	if(chooseids.length != 1 ){
		parent.$.messager.alert(var_alert_title, var_fobcost_onlyone_select, 'info');
		return false;
	}

	return true;
}
//选定Fob成本记录后，将值赋给父页面
function selectFobCostContract(){
	parent.$.messager.progress({
        title : var_alert_title,
        text : var_loadMsg
    });
	
	if(!checkFobCostChoose()){
		parent.$.messager.progress('close');
        return false;
     }else{
 		$(itemEditor.target).val(fobCostItem);
 		$(itemSizeEditor.target).val(fobCostISize);
    	 parent.$.messager.progress('close');
     }
	
	parent.$.modalDialog2.handler.dialog('close');//要先关闭弹出框，才能另外打开
}
//打开二级页面
function showSecondDialog(title,url,target){
	parent.$.modalDialog2({
		title : title,
		iconCls:"icon-tip",
		width:750,
		height:500,
		href : url,
		buttons:[{ 
			text : var_confirm,
			iconCls : 'icon-ok',
			handler : function() {
				if(target == "crmcus"){
					selectTradeCusContract();
				}
				if(target == "fobcost"){
					selectFobCostContract();
				}
			}
		}, {
			text : var_cancel,
			iconCls : 'icon-cancel',
			handler : function() {
				parent.$.modalDialog2.handler.dialog('close');
		   } 
		}]
	});
}